<?php

/**
 * user actions.
 *
 * @package    makethetouch
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions {

    public function executeRegister(sfWebRequest $request) {
        $this->getUser()->getMenu()->setMenuEntry(menu::NONE);
        $this->form = new PersonForm();
        $this->setTemplate('new');
    }

    public function executeCreateAccount(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));
        $this->form = new PersonForm();
        $this->setTemplate('new');
        $this->processForm($request, $this->form);
    }

    protected function getActivationCode(Person $person) {
        return substr(md5($person->getSubscriptionip() . $person->getLogin() . $person->getSubscriptiondate()), 0, 8);
    }

    protected function processForm(sfWebRequest $request, PersonForm $form) {
        $form->bind($request->getParameter($form->getName()));
        if ($form->isValid()) {
            // The form is not valid
            $person = $form->getObject();
            if ($person->getSubscriptionip()) {
                //update the existing account
                $person = $form->save();
            } else {
                //create a new account
                $person->setSubscriptionip($_SERVER['REMOTE_ADDR']);
                $person->setSubscriptiondate(date('Y-m-d H:i:s'));
                $person->setLevel(1); // 1 = Member / 9 = Admin
                $person->setStatus(0); // 0 = disabled / 1 = enabled / 2 = forbidden
                $person = $form->save();

                // Send and email to ask the account validation
                try {
                    $mailer = $this->getMailer();
                    $from = sfConfig::get('app_site_emailnoreply');
                    $to = $person->getEmail();
                    $subject = 'MakeTheTouch.org: Confirmation';
                    $mailContext = array("code" => $this->getActivationCode($person), "login" => $person->getLogin());
                    $body = $this->getPartial('mail/confirmationCreationHtml', $mailContext);

                    $message = $mailer->compose($from, $to, $subject);
                    $message->setBody($body, 'text/html');
                    $this->getMailer()->send($message, $to, $from);
                    //TODO show a page indicating the user should read its mails.
                    $this->redirect('localized_homepage');
                } catch (Exception $e) {
                    echo 'Error:'.$e->getMessage().'<br>';
                }
            }
        } else {
            // The form is not valid
        }
    }

    public function executeValidate(sfWebRequest $request) {
        $login = $request->getParameter('login');
        $activationCode = $request->getParameter('code');
        $this->logMessage('validating...'.$login.' with '.$activationCode.' ...', 'err');
        if ($login == null || $activationCode == null) {
            $this->redirect('localized_homepage');
        }


        $person = Doctrine::getTable('Person')->findOneBy('login', $login);
        if ($person == null) {
            $this->logMessage('Bad login!', 'err');
            $this->redirect('localized_homepage');
        }
        if ($person->getStatus() == 0) {
            //the account is not activated => activate it
            $db_activationCode = $this->getActivationCode($person);
            if ($activationCode != $db_activationCode) {
                $this->logMessage('Bad activation code', 'err');
                $this->redirect('localized_homepage');
            }
            $person->setStatus(1);
            $person->save();
            
            // auto login the user
            $this->doLogin($person);
        //} else { //the account has been already activated
        }
        $this->redirect('localized_homepage');
    }

    public function executeLogin(sfWebRequest $request) {
        $this->getUser()->getMenu()->setMenuEntry(menu::NONE);
        $this->form = new LoginForm();
    }

    public function executeDoLogin(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod('post'));
        $this->form = new LoginForm();
        $values = $request->getParameter('login');
        $this->form->bind($values);
        if ($this->form->isValid()) {
            $login = $values['login'];
            $person = Doctrine::getTable('Person')->findOneByLogin($login);
            $this->doLogin($person);
            $this->redirect('localized_homepage');
        } else {
            $this->setTemplate("login");
        }
    }

    private function doLogin(Person $person) {
            // Remember the user is Authenticated in the session
            $this->getUser()->setAuthenticated(true);

            $this->getUser()->setPerson($person);

            // Add credential in the session
            switch ($person->getLevel()) {
                case 1:
                    $this->getUser()->addCredential("member");
                    break;
                case 9:
                    $this->getUser()->addCredential("admin");
                    break;
                default:
                    $this->getUser()->addCredential("member");
            }
    }

    public function executeLogout(sfWebRequest $request) {
        // Supprime l'état identifié de l'user
        $this->getUser()->setAuthenticated(false);

        // Supprime tous les accès de l'user
        $this->getUser()->clearCredentials();

        // Supprime les valeurs de la sessions que l'on a stocké
        $this->getUser()->setPerson(null);

        $this->redirect('localized_homepage');
    }

    public function executeDelete(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($person = Doctrine_Core::getTable('Person')->find(array($request->getParameter('login'))), sprintf('Object person does not exist (%s).', $request->getParameter('login')));
        $person->delete();

        $this->redirect('user/index');
    }

    public function executeEdit(sfWebRequest $request) {
        $this->forward404Unless($person = Doctrine_Core::getTable('Person')->find(array($request->getParameter('login'))), sprintf('Object person does not exist (%s).', $request->getParameter('login')));
        $this->form = new PersonForm($person);
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($person = Doctrine_Core::getTable('Person')->find(array($request->getParameter('login'))), sprintf('Object person does not exist (%s).', $request->getParameter('login')));
        $this->form = new PersonForm($person);

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeIndex(sfWebRequest $request) {
        $this->persons = Doctrine_Core::getTable('Person')
                        ->createQuery('a')
                        ->execute();
    }

    public function executeShow(sfWebRequest $request) {
        $this->person = Doctrine_Core::getTable('Person')->find(array($request->getParameter('login')));
        $this->forward404Unless($this->person);
    }

}
